package org.webdb.jdbc;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

public class JDBCExecutionContext {

    protected ResultSet resultSet = null;
    private List<Object[]> generatedKeys = null;

    public JDBCExecutionContext(boolean executionResult, Statement stmt)
            throws SQLException {
        if (executionResult) {
            resultSet = stmt.getResultSet();
        } else {
        }
    }

    public JDBCExecutionContext(int updateCount, Statement stmt)
            throws SQLException {
        defineGeneratedKeys(stmt);
    }

    private void defineGeneratedKeys(Statement stmt) throws SQLException {
        List<Object[]> tk = new LinkedList<Object[]>();
        ResultSet rs = stmt.getGeneratedKeys();
        LinkedList<Object> keys = new LinkedList<Object>();
        while (rs.next()) {
            for (int i = 1; i <= rs.getMetaData().getColumnCount(); i++) {
                keys.add(rs.getObject(i));
            }
            tk.add(keys.toArray(new Object[keys.size()]));
            keys.clear();
        }
        generatedKeys = new ArrayList<Object[]>(tk);
    }

    public List<Object[]> getGeneratedKeys() {
        return generatedKeys;
    }

    public Object getGeneratedKey(int row, int column) {
        Object[] rowData = generatedKeys.get(row);
        return rowData[column];
    }

    public boolean hasGeneratedKeys() {
        return !generatedKeys.isEmpty();
    }
}
